chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  const data = request.data;
  notification(`翻译结果: ${data}`);
  sendResponse('ok');
});

const notificationArr = [];

// 更新bottom
const updateBottom = () => {
  for (let i = 0; i < notificationArr.length; i++) {
    notificationArr[i].div.style.bottom = `${i * 60 + 16}px`;
  }
};

// 通知展示
const notification = (message) => {
  let div = document.createElement('div');
  div.innerText = message;
  div.className = 'miantiao-notification';
  document.body.appendChild(div);
  const id = Date.now() + ~~(Math.random() * 1000);
  div.setAttribute('mid', id);
  notificationArr.push({
    id,
    div,
  });
  updateBottom();

  setTimeout(() => {
    div.style.transform = 'translateX(0)';
    div.style.opacity = 1;
    div.addEventListener('click', (e) => {
      navigator.clipboard.writeText(message);
      alert('翻译结果已复制');
    });
  }, 100);
  let isFocus = false;
  const createTimer = () => {
    return setTimeout(() => {
      div.style.transform = 'translateX(-100%)';
      div.style.opacity = 0;
      div.addEventListener('transitionend', (e) => {
        const id = e.target.getAttribute('mid') * 1;
        const index = notificationArr.findIndex((item) => item.id === id);
        if (index > -1) {
          notificationArr.splice(index, 1);
          e.target.remove();
          div = null;
          updateBottom();
        }
      });
    }, 5000);
  };
  let timer = createTimer();
  div.addEventListener('mouseenter', () => {
    if (timer) {
      clearTimeout(timer);
    }
  });
  div.addEventListener('mouseleave', () => {
    timer = createTimer();
  });
};

// 节流
const throttle = (func, wait = 0, execFirstCall) => {
  let timeout = null;
  let args;
  let firstCallTimestamp;
  function throttled(...arg) {
    if (!firstCallTimestamp) firstCallTimestamp = Date.now();
    if (!execFirstCall || !args) {
      console.log('set args:', arg);
      args = arg;
    }
    if (timeout) {
      clearTimeout(timeout);
    }
    // 以Promise的形式返回函数执行结果
    return new Promise(async (res, rej) => {
      if (Date.now() - firstCallTimestamp >= wait) {
        try {
          const result = await func.apply(this, args);
          res(result);
        } catch (e) {
          rej(e);
        } finally {
          cancel();
        }
      } else {
        timeout = setTimeout(async () => {
          try {
            const result = await func.apply(this, args);
            res(result);
          } catch (e) {
            rej(e);
          } finally {
            cancel();
          }
        }, firstCallTimestamp + wait - Date.now());
      }
    });
  }
  // 允许取消
  function cancel() {
    clearTimeout(timeout);
    args = null;
    timeout = null;
    firstCallTimestamp = null;
  }
  // 允许立即执行
  function flush() {
    cancel();
    return func.apply(this, args);
  }
  throttled.cancel = cancel;
  throttled.flush = flush;
  return throttled;
};

const handleKeydown = (e) => {
  const text = document.getSelection().toString();
  if (!text) {
    return;
  }
  if (e.shiftKey && e.key === 'Z') {
    // 搜索
    chrome.runtime.sendMessage({ command: 'search', text });
  } else if (e.shiftKey && e.key === 'X') {
    // 翻译
    chrome.runtime.sendMessage({ command: 'translate', text });
  }
};

const throttledKeydownFunc = throttle(handleKeydown, 300);

// 监听键盘按下事件
document.addEventListener('keydown', (e) => {
  throttledKeydownFunc(e);
});
